package com.instpower.things.instpower;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.timeout.IdleStateHandler;

import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName ServerInitializer
 * @Author: hellmash@gmail.com
 * @Date: 2020/2/24
 * @Version: 1.0.0
 * @Description: TODO
 */
public class InstpowerServerInitializer extends ChannelInitializer<SocketChannel> {


    @Override
    protected void initChannel(SocketChannel channel) throws Exception {
        ChannelPipeline pipeline = channel.pipeline();
        final LengthFieldBasedFrameDecoder dec = new LengthFieldBasedFrameDecoder(1024 * 1024, 22, 2, 4, 0);
        //心跳时间5 分钟
        pipeline.addFirst("idleStateHandler", new IdleStateHandler(0, 0, 1, TimeUnit.MINUTES));
        LoggingHandler logger =   new LoggingHandler("CORE",LogLevel.DEBUG);
        pipeline.addLast("logger", logger);
        pipeline.addLast("lengthFieldBasedFrameDecoder", dec);
        pipeline.addLast("InstpowerMessageDecoder",new InstpowerMessageDecoder());
        pipeline.addLast("InstpowerMessageEncoder", new InstpowerMessageEncoder());
        pipeline.addLast("InstpowerHandler", new InstpowerHandler());

        initMTHandler();
    }

    private void initMTHandler()
    {
        /**
         * 初始化请求处理器,利用spring容器初始化handler集
         */
        Map<String, Handler> handlers = Context.getBeansOfType(Handler.class);
        for (String key : handlers.keySet())
        {
            Handler handler = handlers.get(key);
            HandlerManager.getInstance().register(handler);
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception
    {
        super.exceptionCaught(ctx, cause);
    }
}
